<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible &&
        !detailInfo.visible &&
        !assetDetailInfo.visible &&
        !assetAnalysisPlansDetailInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
          :filter-btn="filterInfo.btn"
        >
          <template v-slot:filter-operateTime>
            <el-date-picker
              v-model="operateTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="至"
              :clearable="true"
              :picker-options="$fn.pickerOptionsFn()"
              align="right"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="$fn.pickerOptionsFn()"
              :default-time="[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 1, 1, 23, 59, 59),
              ]"
              @change="timeChange"
            ></el-date-picker>
          </template>
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-upload>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :data="uploadInfo.data"
              :on-error="uploadError"
              :on-success="importOrders"
              :before-upload="beforeUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入</el-button>
            </el-upload>
          </template>
          <template v-slot:filter-del>
            <el-button :disabled="!canDelete" @click="del()">删除</el-button>
          </template>
        </NewPageFilter>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-assetCode="scope">
          <span
            v-if="scope.row.assetCode"
            class="slip-edit"
            @click="showAssetDetails(scope.row)"
            >{{ scope.row.assetCode }}</span
          >
          <span v-else>-</span>
        </template>
        <template v-slot:col-planNo="scope">
          <span
            v-if="scope.row.planNo"
            class="slip-edit"
            @click="showAnalysisPlansDetails(scope.row)"
            >{{ scope.row.planNo }}</span
          >
          <span v-else>-</span>
        </template>
      </TableContainer>
    </div>
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :orderId="modifyInfo.orderId"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />
    <!-- 明细信息-预留 -->
    <Detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.id"
      @returnBack="getList"
    />
    <AssetCardDetail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      @returnBack="getList"
    />
    <!-- 方案明细信息 -->
    <AssetAnalysisPlansDetail
      v-if="assetAnalysisPlansDetailInfo.visible"
      v-model:visible="assetAnalysisPlansDetailInfo.visible"
      :onlyShow="true"
      :id="assetAnalysisPlansDetailInfo.id"
    />
    <SelectFiscalPeriod
      v-if="selectFiscalPeriodInfo.visible"
      v-model:show-dialog="selectFiscalPeriodInfo.visible"
      :api="getBaseFiscalPeriodPage"
      :save-empty="false"
      :check-box="false"
      :highlight-row="true"
      :query="selectFiscalPeriodInfo.query"
      @callback="callBackSelectFiscalPeriod"
    />
    <ExcelOrPrint :excelPrint="excelPrint"></ExcelOrPrint>
  </div>
</template>

<script setup name="analysisDepreciation">
import { ElLoading } from 'element-plus'
import {
  getAnalysisDepreciationPage,
  delAnalysisDepreciation,
  exportAnalysisDepreciation,
  exportTempAnalysisDepreciation,
  reCalcAnalysisDepreciation,
} from '@/api/asset'
import { getBaseFiscalPeriodPage } from '@/api/base'
import { getDeptAll } from '@/api/core'
const Modify = defineAsyncComponent(() => import('./modify'))
const Detail = defineAsyncComponent(() => import('./detail'))
const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)
const AssetAnalysisPlansDetail = defineAsyncComponent(() =>
  import('@/views/asset/analy/assetAnalysisPlans/detail')
)
import axios from 'axios'

const { proxy } = getCurrentInstance()

const operateTime = ref([])
const selectFiscalPeriodInfo = ref({
  visible: false,
  query: {
    fiscalType: 2,
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
  },
  copyQuery: {},
  list: [
    {
      slot: true,
      label: '起止日期',
      value: 'operateTime',
      event: search,
    },
    {
      componentType: 'input',
      label: '资产名称',
      value: 'assetName',
      event: search,
    },
    {
      componentType: 'input',
      label: '资产卡片号',
      value: 'assetCode',
      event: search,
    },
    {
      componentType: 'input',
      label: '厂家',
      value: 'brandName',
      event: search,
    },
    {
      label: '使用部门',
      value: 'useDeptIdMult',
      query: {
        deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      label: '管理部门',
      value: 'manageDeptId',
      query: {
        deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: false,
      event: search,
    },
    {
      asValue: 'sourceType',
      componentType: 'select-model',
      code: 'data_source',
      label: '数据来源',
      event: search,
    },
    {
      componentType: 'input',
      label: '分析方案编码',
      value: 'planNo',
      event: search,
    },
    {
      componentType: 'input',
      label: '分析方案名称',
      value: 'planName',
      event: search,
    },
  ],
  btn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('analysisDepreciation:add'),
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemp,
      show: proxy.$permission('analysisDepreciation:download'),
    },
    {
      type: 'slot',
      value: 'upload',
      show: proxy.$permission('analysisDepreciation:import'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('analysisDepreciation:exportExcel'),
    },
    {
      type: 'slot',
      value: 'del',
      show: proxy.$permission('analysisDepreciation:del'),
    },
    {
      type: 'button',
      label: '重新计算',
      event: recalculate,
      show: proxy.$permission('analysisDepreciation:recalculate'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: getAnalysisDepreciationPage,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '日期',
      value: 'businessDate',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'slot',
    },
    {
      label: '资产名称',
      value: 'assetName',
    },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '使用部门', value: 'useDeptName' },
    { label: '管理部门', value: 'manageDeptName' },
    { label: '数据来源', value: 'sourceTypeValue' },
    {
      label: '分析方案编码',
      value: 'planNo',
      type: 'slot',
    },
    { label: '分析方案名称', value: 'planName' },
    { label: '分析部门', value: 'deptName' },
    {
      label: '设备折旧费用',
      value: 'amount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('analysisDepreciation:update'),
        ifRender: function (row) {
          return row.sourceType !== 4
        },
      },
      {
        label: '删除',
        event: del,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('analysisDepreciation:del'),
        ifRender: function (row) {
          return row.sourceType !== 4
        },
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
})
//打印
const excelPrint = ref({
  type: 'print', // 类型print/excel
  excel: {
    api: exportAnalysisDepreciation, // 导出数据接口
    params: {}, // 导出参数
  },
  refresh: null,
})
const page = ref({
  page: true,
  pageSize: 20,
  curPage: 1,
})
const uploadInfo = ref({
  action:
    axios.defaults.baseURL + '/asset/analysisDepreciation/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
  data: {
    supplierId: '',
  },
})
const assetAnalysisPlansDetailInfo = ref({
  visible: false,
  id: '',
})

const canDelete = computed(() => {
  return tableInfo.value.selections.length && isAllSourceTypeNot4()
})

onMounted(() => {
  filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query)
})

function isAllSourceTypeNot4() {
  let arr = tableInfo.value.selections.filter((element) => {
    return element.sourceType !== 4
  })
  return arr.length === tableInfo.value.selections.length
}

function importOrders(resp) {
  //导入
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function beforeUpload() {
  //导入
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  return true
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.startDate = val[0]
    filterInfo.value.query.endDate = val[1]
  } else {
    filterInfo.value.query.startDate = ''
    filterInfo.value.query.endDate = ''
  }
  search()
}
function returnModify() {
  getList()
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQuery)
  operateTime.value = []
  search()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//创建
function create() {
  modifyInfo.value.title = '新增支出数据'
  modifyInfo.value.visible = true
  modifyInfo.value.orderId = null
}
function downloadTemp() {
  exportTempAnalysisDepreciation().then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
//更新
function update(row) {
  modifyInfo.value.title = '修改支出费用'
  modifyInfo.value.orderId = row.id
  modifyInfo.value.visible = true
}
function pageInfo(obj) {
  page.value = obj
}
//导出
function exportExcel() {
  excelPrint.value.type = 'excel'
  excelPrint.value.excel.params = proxy.$fn.deepClone({
    ...proxy.$fn.delEmptyAttribute(filterInfo.value.query),
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}
function recalculate() {
  selectFiscalPeriodInfo.value.visible = true
}
function callBackSelectFiscalPeriod(data) {
  reCalcAnalysisDepreciation(data).then((res) => {
    if (res && res.success) {
      search()
    }
  })
}
function showAssetDetails(row) {
  if (row.assetId && row.assetId !== -2) {
    assetDetailInfo.value.id = row.assetId
    assetDetailInfo.value.visible = true
  }
}
function showAnalysisPlansDetails(row) {
  assetAnalysisPlansDetailInfo.value.id = row.analysisPlanId
  assetAnalysisPlansDetailInfo.value.visible = true
}
//删除
function del(row = undefined) {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      const ids = _getIds(row)
      delAnalysisDepreciation(ids).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
function _getIds(row) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    if (tableInfo.value.selections.length > 0) {
      ids = tableInfo.value.selections.map((row) => row.id)
    }
  }
  return ids
}
</script>

<style scoped></style>
